<template>
  <el-config-provider :locale="zhCn">
    <div class="page">
      <div class="toolbar">
        <el-form :inline="true" :model="filters" class="filters">
          <template v-if="activeTab==='providers'">
            <el-form-item label="编码"><el-input v-model="filters.p_code" placeholder="请输入" clearable /></el-form-item>
            <el-form-item label="名称"><el-input v-model="filters.p_name" placeholder="请输入" clearable /></el-form-item>
            <el-form-item label="认证"><el-select v-model="filters.p_auth" placeholder="请选择" clearable><el-option label="api_key" value="api_key" /><el-option label="bearer" value="bearer" /><el-option label="oauth2" value="oauth2" /></el-select></el-form-item>
            <el-form-item label="启用"><el-select v-model="filters.p_enabled" placeholder="全部" clearable><el-option label="是" :value="true" /><el-option label="否" :value="false" /></el-select></el-form-item>
          </template>
          <template v-else-if="activeTab==='models'">
            <el-form-item label="供应商"><el-select v-model="filters.m_provider" placeholder="全部" clearable><el-option v-for="p in providers" :key="p.id" :label="p.name" :value="p.id" /></el-select></el-form-item>
            <el-form-item label="编码"><el-input v-model="filters.m_code" placeholder="请输入" clearable /></el-form-item>
            <el-form-item label="显示名"><el-input v-model="filters.m_name" placeholder="请输入" clearable /></el-form-item>
            <el-form-item label="启用"><el-select v-model="filters.m_enabled" placeholder="全部" clearable><el-option label="是" :value="true" /><el-option label="否" :value="false" /></el-select></el-form-item>
          </template>
          <template v-else>
            <el-form-item label="供应商"><el-select v-model="filters.s_provider" placeholder="全部" clearable><el-option v-for="p in providers" :key="p.id" :label="p.name" :value="p.id" /></el-select></el-form-item>
            <el-form-item label="名称"><el-input v-model="filters.s_name" placeholder="请输入" clearable /></el-form-item>
            <el-form-item label="版本"><el-input v-model.number="filters.s_version" placeholder="请输入" clearable /></el-form-item>
            <el-form-item label="启用"><el-select v-model="filters.s_enabled" placeholder="全部" clearable><el-option label="是" :value="true" /><el-option label="否" :value="false" /></el-select></el-form-item>
          </template>
          <el-form-item>
            <el-button type="primary" @click="reload">查询</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </el-form-item>
        </el-form>
        <div class="actions">
          <el-button type="primary" v-if="activeTab==='providers'" @click="openProviderCreate">新建供应商</el-button>
          <el-button type="primary" v-if="activeTab==='models'" @click="openModelCreate">新建模型</el-button>
          <el-button type="primary" v-if="activeTab==='secrets'" @click="openSecretCreate">新建密钥</el-button>
        </div>
      </div>

      <div class="table-area">
        <div class="table-container">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="供应商" name="providers">
              <el-table :data="filteredProviders" style="width:100%">
                <el-table-column prop="code" label="编码" min-width="160" />
                <el-table-column prop="name" label="名称" min-width="180" />
                <el-table-column prop="base_url" label="Base URL" min-width="220" />
                <el-table-column prop="auth_type" label="认证" min-width="120" />
                <el-table-column prop="enabled" label="启用" min-width="100">
                  <template #default="{ row }">{{ row.enabled ? '是' : '否' }}</template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="300">
                  <template #default="{ row }">
                    <el-button @click="openProviderEdit(row)">编辑</el-button>
                    <el-popconfirm title="确定删除该供应商？" @confirm="removeProvider(row)">
                      <template #reference><el-button type="danger">删除</el-button></template>
                    </el-popconfirm>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>

            <el-tab-pane label="模型" name="models">
              <el-table :data="filteredModels" style="width:100%">
                <el-table-column label="供应商" min-width="160">
                  <template #default="{ row }">{{ providerName(row.provider_id) }}</template>
                </el-table-column>
                <el-table-column prop="code" label="编码" min-width="160" />
                <el-table-column prop="display_name" label="显示名" min-width="180" />
                <el-table-column prop="context_window" label="上下文" min-width="120" />
                <el-table-column prop="max_output_tokens" label="最大输出" min-width="120" />
                <el-table-column prop="default_temperature" label="温度" min-width="100" />
                <el-table-column prop="enabled" label="启用" min-width="100">
                  <template #default="{ row }">{{ row.enabled ? '是' : '否' }}</template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="300">
                  <template #default="{ row }">
                    <el-button @click="openModelEdit(row)">编辑</el-button>
                    <el-popconfirm title="确定删除该模型？" @confirm="removeModel(row)">
                      <template #reference><el-button type="danger">删除</el-button></template>
                    </el-popconfirm>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>

            <el-tab-pane label="密钥库" name="secrets">
              <el-table :data="filteredSecrets" style="width:100%">
                <el-table-column label="供应商" min-width="160">
                  <template #default="{ row }">{{ providerName(row.provider_id) }}</template>
                </el-table-column>
                <el-table-column prop="name" label="名称" min-width="160" />
                <el-table-column prop="enabled" label="启用" min-width="100">
                  <template #default="{ row }">{{ row.enabled ? '是' : '否' }}</template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="300">
                  <template #default="{ row }">
                    <el-button @click="openSecretEdit(row)">编辑</el-button>
                    <el-popconfirm title="确定删除该密钥？" @confirm="removeSecret(row)">
                      <template #reference><el-button type="danger">删除</el-button></template>
                    </el-popconfirm>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>

      <el-dialog v-model="providerDialog.show" :title="providerDialog.title" width="640px" destroy-on-close>
        <el-form ref="providerFormRef" :model="providerForm" :rules="providerRules" label-width="130px">
          <el-form-item v-if="!providerDialog.editingId" label="常用供应商">
            <el-select v-model="selectedBuiltin" placeholder="请选择" clearable @change="applyBuiltin">
              <el-option v-for="bp in builtinProviders" :key="bp.code" :label="bp.name" :value="bp.code" />
            </el-select>
          </el-form-item>
          <el-form-item label="编码" prop="code"><el-input v-model="providerForm.code" :disabled="!!providerDialog.editingId" /></el-form-item>
          <el-form-item label="名称" prop="name"><el-input v-model="providerForm.name" /></el-form-item>
          <el-form-item label="Base URL"><el-input v-model="providerForm.base_url" /></el-form-item>
          <el-form-item label="认证" prop="auth_type"><el-select v-model="providerForm.auth_type"><el-option label="api_key" value="api_key" /><el-option label="bearer" value="bearer" /><el-option label="oauth2" value="oauth2" /></el-select></el-form-item>
          <el-form-item label="启用"><el-switch v-model="providerForm.enabled" /></el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="providerDialog.show=false">取消</el-button>
          <el-button type="primary" :loading="saving" @click="submitProvider">保存</el-button>
        </template>
      </el-dialog>

      <el-dialog v-model="modelDialog.show" :title="modelDialog.title" width="640px" destroy-on-close>
        <el-form ref="modelFormRef" :model="modelForm" :rules="modelRules" label-width="130px">
          <el-form-item label="供应商" prop="provider_id"><el-select v-model="modelForm.provider_id"><el-option v-for="p in providers" :key="p.id" :label="p.name" :value="p.id" /></el-select></el-form-item>
          <el-form-item label="编码" prop="code"><el-input v-model="modelForm.code" :disabled="!!modelDialog.editingId" /></el-form-item>
          <el-form-item label="显示名" prop="display_name"><el-input v-model="modelForm.display_name" /></el-form-item>
          <el-form-item label="上下文"><el-input v-model.number="modelForm.context_window" /></el-form-item>
          <el-form-item label="最大输出"><el-input v-model.number="modelForm.max_output_tokens" /></el-form-item>
          <el-form-item label="温度"><el-input v-model.number="modelForm.default_temperature" /></el-form-item>
          <el-form-item label="启用"><el-switch v-model="modelForm.enabled" /></el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="modelDialog.show=false">取消</el-button>
          <el-button type="primary" :loading="saving" @click="submitModel">保存</el-button>
        </template>
      </el-dialog>

      <el-dialog v-model="secretDialog.show" :title="secretDialog.title" width="640px" destroy-on-close>
        <el-form ref="secretFormRef" :model="secretForm" :rules="secretRules" label-width="160px">
          <el-form-item label="供应商" prop="provider_id"><el-select v-model="secretForm.provider_id"><el-option v-for="p in providers" :key="p.id" :label="p.name" :value="p.id" /></el-select></el-form-item>
          <el-form-item label="名称" prop="name"><el-input v-model="secretForm.name" /></el-form-item>
          <el-form-item label="密钥" prop="secret_value"><el-input v-model="secretForm.secret_value" type="textarea" /></el-form-item>
          <el-form-item label="启用"><el-switch v-model="secretForm.enabled" /></el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="secretDialog.show=false">取消</el-button>
          <el-button type="primary" :loading="saving" @click="submitSecret">保存</el-button>
        </template>
      </el-dialog>
    </div>
  </el-config-provider>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { ElMessage } from 'element-plus'
import { api } from '../../api/client'

interface Provider { id: string, code: string, name: string, base_url?: string, auth_type: string, enabled: boolean }
interface Model { id: string, provider_id: string, code: string, display_name: string, context_window?: number, max_output_tokens?: number, default_temperature?: number, enabled: boolean }
interface Secret { id: string, provider_id: string, name: string, cipher_algo: string, key_id: string, rotation_version: number, enabled: boolean }

const providers = ref<Provider[]>([])
const models = ref<Model[]>([])
const secrets = ref<Secret[]>([])
const activeTab = ref<'providers'|'models'|'secrets'>('providers')

const filters = reactive({
  p_code: '', p_name: '', p_auth: '', p_enabled: undefined as undefined|boolean,
  m_provider: '', m_code: '', m_name: '', m_enabled: undefined as undefined|boolean,
  s_provider: '', s_name: '', s_version: undefined as undefined|number, s_enabled: undefined as undefined|boolean,
})

const filteredProviders = computed(() => {
  let arr = providers.value.slice()
  if (filters.p_code) arr = arr.filter(x => x.code?.includes(filters.p_code))
  if (filters.p_name) arr = arr.filter(x => x.name?.includes(filters.p_name))
  if (filters.p_auth) arr = arr.filter(x => x.auth_type === filters.p_auth)
  if (filters.p_enabled !== undefined) arr = arr.filter(x => x.enabled === filters.p_enabled)
  return arr
})

const filteredModels = computed(() => {
  let arr = models.value.slice()
  if (filters.m_provider) arr = arr.filter(x => x.provider_id === filters.m_provider)
  if (filters.m_code) arr = arr.filter(x => x.code?.includes(filters.m_code))
  if (filters.m_name) arr = arr.filter(x => x.display_name?.includes(filters.m_name))
  if (filters.m_enabled !== undefined) arr = arr.filter(x => x.enabled === filters.m_enabled)
  return arr
})

const filteredSecrets = computed(() => {
  let arr = secrets.value.slice()
  if (filters.s_provider) arr = arr.filter(x => x.provider_id === filters.s_provider)
  if (filters.s_name) arr = arr.filter(x => x.name?.includes(filters.s_name))
  if (filters.s_version !== undefined) arr = arr.filter(x => x.rotation_version === filters.s_version)
  if (filters.s_enabled !== undefined) arr = arr.filter(x => x.enabled === filters.s_enabled)
  return arr
})

const providerDialog = ref({ show: false, title: '', editingId: null as null|string })
const modelDialog = ref({ show: false, title: '', editingId: null as null|string })
const secretDialog = ref({ show: false, title: '', editingId: null as null|string })
const saving = ref(false)

const providerFormRef = ref()
const modelFormRef = ref()
const secretFormRef = ref()

const providerForm = ref<Partial<Provider>>({ code: '', name: '', base_url: '', auth_type: 'api_key', enabled: true })
const modelForm = ref<Partial<Model>>({ provider_id: '', code: '', display_name: '', context_window: undefined, max_output_tokens: undefined, default_temperature: undefined, enabled: true })
const secretForm = ref<any>({ provider_id: '', name: 'api_key', secret_value: '', enabled: true })

const providerRules = { code: [{ required: true, message: '请输入编码', trigger: 'blur' }], name: [{ required: true, message: '请输入名称', trigger: 'blur' }], auth_type: [{ required: true, message: '请选择认证方式', trigger: 'change' }] }
const modelRules = { provider_id: [{ required: true, message: '请选择供应商', trigger: 'change' }], code: [{ required: true, message: '请输入编码', trigger: 'blur' }], display_name: [{ required: true, message: '请输入显示名', trigger: 'blur' }] }
const secretRules = { provider_id: [{ required: true, message: '请选择供应商', trigger: 'change' }], name: [{ required: true, message: '请输入名称', trigger: 'blur' }], secret_value: [{ required: true, message: '请输入密钥', trigger: 'blur' }] }

const builtinProviders = [
  { code: 'deepseek', name: 'DeepSeek', base_url: 'https://api.deepseek.com', auth_type: 'bearer' },
  { code: 'kimi', name: 'Kimi', base_url: 'https://api.moonshot.cn/v1', auth_type: 'bearer' },
  { code: 'doubao', name: '豆包', base_url: 'https://api.doubao.com/v1', auth_type: 'bearer' },
  { code: 'aliyun_bailian', name: '阿里百炼', base_url: 'https://dashscope.aliyuncs.com/api/v1', auth_type: 'api_key' },
  { code: 'ollama', name: 'Ollama', base_url: 'http://localhost:11434/api', auth_type: 'api_key' },
]
const selectedBuiltin = ref<string | null>(null)
function applyBuiltin(code: string | null) {
  if (!code) return
  const found = builtinProviders.find(x => x.code === code)
  if (!found) return
  providerForm.value.code = found.code
  providerForm.value.name = found.name
  providerForm.value.base_url = found.base_url
  providerForm.value.auth_type = found.auth_type
}

function providerName(id: string) {
  return providers.value.find(p => p.id === id)?.name || id
}

async function load() {
  const [p, m, s] = await Promise.all([ api.get('/llm/providers'), api.get('/llm/models'), api.get('/llm/secrets') ])
  providers.value = p.data || []
  models.value = m.data || []
  secrets.value = s.data || []
}

function reload() {}
function resetFilters() { filters.p_code=''; filters.p_name=''; filters.p_auth=''; filters.p_enabled=undefined; filters.m_provider=''; filters.m_code=''; filters.m_name=''; filters.m_enabled=undefined; filters.s_provider=''; filters.s_name=''; filters.s_version=undefined; filters.s_enabled=undefined }

function openProviderCreate() { providerDialog.value.title='新建供应商'; providerDialog.value.editingId=null; providerForm.value={ code:'', name:'', base_url:'', auth_type:'api_key', enabled:true }; providerDialog.value.show=true }
function openProviderEdit(row: Provider) { providerDialog.value.title='编辑供应商'; providerDialog.value.editingId=row.id; providerForm.value={ code: row.code, name: row.name, base_url: row.base_url, auth_type: row.auth_type, enabled: row.enabled }; providerDialog.value.show=true }
async function submitProvider() { if (providerFormRef.value){ const ok=await new Promise<boolean>((resolve)=>providerFormRef.value.validate((v:boolean)=>resolve(v))); if(!ok) return } saving.value=true; try { if (providerDialog.value.editingId){ const id=providerDialog.value.editingId as string; const resp=await api.put(`/llm/providers/${id}`, { name: providerForm.value.name, base_url: providerForm.value.base_url, auth_type: providerForm.value.auth_type, enabled: providerForm.value.enabled }); const idx=providers.value.findIndex(x=>x.id===id); if(idx>=0) providers.value[idx]=resp.data; ElMessage.success('已保存') } else { const resp=await api.post('/llm/providers', providerForm.value); providers.value.unshift(resp.data); ElMessage.success('已创建') } providerDialog.value.show=false } catch(e:any){ const msg=e?.response?.data?.detail||'保存失败'; ElMessage.error(msg) } finally { saving.value=false }
}
async function removeProvider(row: Provider) { await api.delete(`/llm/providers/${row.id}`); providers.value=providers.value.filter(x=>x.id!==row.id); ElMessage.success('已删除') }

function openModelCreate() { modelDialog.value.title='新建模型'; modelDialog.value.editingId=null; modelForm.value={ provider_id:'', code:'', display_name:'', context_window:undefined, max_output_tokens:undefined, default_temperature:undefined, enabled:true }; modelDialog.value.show=true }
function openModelEdit(row: Model) { modelDialog.value.title='编辑模型'; modelDialog.value.editingId=row.id; modelForm.value={ provider_id: row.provider_id, code: row.code, display_name: row.display_name, context_window: row.context_window, max_output_tokens: row.max_output_tokens, default_temperature: row.default_temperature, enabled: row.enabled }; modelDialog.value.show=true }
async function submitModel() { if (modelFormRef.value){ const ok=await new Promise<boolean>((resolve)=>modelFormRef.value.validate((v:boolean)=>resolve(v))); if(!ok) return } if (!modelForm.value.provider_id) return; saving.value=true; try { if (modelDialog.value.editingId){ const id=modelDialog.value.editingId as string; const resp=await api.put(`/llm/models/${id}`, { code: modelForm.value.code, display_name: modelForm.value.display_name, context_window: modelForm.value.context_window, max_output_tokens: modelForm.value.max_output_tokens, default_temperature: modelForm.value.default_temperature, enabled: modelForm.value.enabled }); const idx=models.value.findIndex(x=>x.id===id); if(idx>=0) models.value[idx]=resp.data; ElMessage.success('已保存') } else { const resp=await api.post('/llm/models', modelForm.value); models.value.unshift(resp.data); ElMessage.success('已创建') } modelDialog.value.show=false } catch(e:any){ const msg=e?.response?.data?.detail||'保存失败'; ElMessage.error(msg) } finally { saving.value=false }
}
async function removeModel(row: Model) { await api.delete(`/llm/models/${row.id}`); models.value=models.value.filter(x=>x.id!==row.id); ElMessage.success('已删除') }

function openSecretCreate() { secretDialog.value.title='新建密钥'; secretDialog.value.editingId=null; secretForm.value={ provider_id:'', name:'api_key', secret_value:'', enabled:true }; secretDialog.value.show=true }
function openSecretEdit(row: any) { secretDialog.value.title='编辑密钥'; secretDialog.value.editingId=row.id; secretForm.value={ provider_id: row.provider_id, name: row.name, secret_value:'', enabled: row.enabled }; secretDialog.value.show=true }
async function submitSecret() { if (secretDialog.value.editingId){ const hasSecret = !!secretForm.value.secret_value; const rulesBak = secretFormRef.value?.rules; if (!hasSecret && secretFormRef.value) { secretFormRef.value.rules = { provider_id: secretRules.provider_id, name: secretRules.name } } if (secretFormRef.value){ const ok=await new Promise<boolean>((resolve)=>secretFormRef.value.validate((v:boolean)=>resolve(v))); if(!ok){ if (rulesBak) secretFormRef.value.rules = rulesBak; return } } if (rulesBak) secretFormRef.value.rules = rulesBak } else { if (secretFormRef.value){ const ok=await new Promise<boolean>((resolve)=>secretFormRef.value.validate((v:boolean)=>resolve(v))); if(!ok) return } }
  saving.value=true; try { if (secretDialog.value.editingId){ const id=secretDialog.value.editingId as string; const payload:any = { provider_id: secretForm.value.provider_id, name: secretForm.value.name, enabled: secretForm.value.enabled }; if (secretForm.value.secret_value) payload.secret_value = secretForm.value.secret_value; const resp=await api.put(`/llm/secrets/${id}`, payload); const idx=secrets.value.findIndex(x=>x.id===id); if(idx>=0) secrets.value[idx]=resp.data; ElMessage.success('已保存') } else { const resp=await api.post('/llm/secrets', secretForm.value); secrets.value.unshift(resp.data); ElMessage.success('已创建') } secretDialog.value.show=false } catch(e:any){ const msg=e?.response?.data?.detail||'保存失败'; ElMessage.error(msg) } finally { saving.value=false }
}
async function removeSecret(row: any) { await api.delete(`/llm/secrets/${row.id}`); secrets.value=secrets.value.filter(x=>x.id!==row.id); ElMessage.success('已删除') }

onMounted(load)
</script>

<style scoped>
.page { height: 100%; display: flex; flex-direction: column; box-sizing: border-box; overflow: hidden; padding: 16px; }
.toolbar { flex-shrink: 0; display: flex; align-items: center; justify-content: space-between; gap: 12px; padding-bottom: 16px; box-sizing: border-box; }
.filters { flex: 1; }
.actions { flex-shrink: 0; }
.table-area { flex: 1; display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
.table-container { flex: 1; overflow: hidden; display: flex; flex-direction: column; min-height: 0; position: relative; }
.table-container :deep(.el-table) { height: 100% !important; display: flex; flex-direction: column; flex: 1; }
.table-container :deep(.el-table__inner-wrapper) { height: 100% !important; display: flex; flex-direction: column; flex: 1; }
.table-container :deep(.el-table__header-wrapper) { flex-shrink: 0; height: auto !important; }
.table-container :deep(.el-table__body-wrapper) { flex: 1; overflow-y: auto !important; height: auto !important; min-height: 200px; }
.table-container :deep(.el-table__empty-block) { min-height: 200px; display: flex; align-items: center; justify-content: center; }
@media (max-width: 768px) { .toolbar { flex-direction: column; align-items: stretch; } .filters { margin-bottom: 12px; } }
</style>